<template>
  <div>
    <el-form :inline="true" label-width="80px">
      <el-form-item>
        <el-input v-model="tempSearchObj.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <!-- 查询与情况的按钮 -->
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button type="default" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="danger" :disabled="multiple" @click="handleDeletes">批量删除</el-button>
    </div>
    <!-- table表格：展示用户信息的地方 -->
    <el-table
      v-loading="listLoading"
      :data="pageList"
      style="width:100%"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="150" align="center" />
      <el-table-column prop="nickName" label="用户昵称" width="width" align="center" />
      <el-table-column prop="roleName" label="权限列表" width="width" align="center" />
      <el-table-column prop="gmtCreate" label="创建时间" width="200" align="center" />
      <el-table-column prop="gmtModified" label="更新时间" width="200" align="center" />
      <el-table-column label="操作" width="width" align="center">
        <template slot-scope="{row, $index}">
          <div>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="bottom-end">
              <el-button type="info" icon="el-icon-user" size="mini" @click="showAssignRole(row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改用户" placement="bottom-end">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showUpdateUser(row)"
              />
            </el-tooltip>
            <!-- <el-tooltip class="item" effect="dark" content="删除用户" placement="bottom-end">
              <el-popconfirm title="确定删除$吗？" @onConfirm="removeUser(row.id)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" @click="showUpdateUser(row)" />
              </el-popconfirm>
            </el-tooltip>-->

            <el-tooltip class="item" effect="dark" content="删除用户" placement="bottom-end">
              <el-popconfirm title="确定删除$吗？" @onConfirm="removeUser(row, row.id)">
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  style="margin-left:10px"
                />
              </el-popconfirm>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      background
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[3, 10, 20, 30, 40, 50, 100]"
      style="padding: 20px 0;"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getUsers"
      @size-change="handleSizeChange"
    />
    <!-- <div style="display: flex; justify-content: flex-end; margin-top: 20px">
      <pagination
        v-show="queryParams.total > 0"
        :total="queryParams.total"
        :page.sync="queryParams._page"
        :limit.sync="queryParams._limit"
        style="margin-top: 0px; padding-top: 0px"
        @pagination="handleQuery"
      />
    </div>-->
    <!-- 添加或者修改用户的对话框 -->
    <el-dialog :title="user.id ? '修改用户' : '添加用户'" :visible.sync="dialogUserVisible">
      <el-form ref="userForm" :model="user" :rules="userRules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName" placeholder="用户昵称" />
        </el-form-item>
        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input v-model="user.password" placeholder="用户密码" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色对话框 -->
    <el-dialog title="设置角色" :visible.sync="dialogRoleVisible" :before-close="resetRoleData">
      <el-form label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input disabled :value="user.username" />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox
              v-for="(role, index) in allRoles"
              :key="role.id"
              :label="role.id"
            >{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button :loading="loading" type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
export default {
  name: 'PermissionUser',
  components: { Pagination },
  data() {
    return {
      listLoading: false, // 是否显示列表加载的提示
      // 批量删除id数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      page: 1, // 当前页码
      limit: 3, // 每页数量
      total: 0, // 总数量
      searchObj: {
        // 包含请求搜索条件数据的对象
        username: ''
      },
      tempSearchObj: {
        // 收集搜索条件输入的对象
        username: ''
      },
      queryParams: {
        total: 0,
        _page: 1,
        _limit: 10
      },
      // 当前页的用户列表
      pageList: [],
      user: {}, // 当前要操作的user
      // 对话框
      dialogUserVisible: false,
      // 设置角色对话框
      dialogRoleVisible: false,
      // 验证规则
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: '用户名必须输入' },
          { min: 4, message: '用户名不能小于4位' }
        ],
        password: [{ required: true, validator: this.validatePassword }]
      },
      // 所有角色列表
      allRoles: [],
      // 用户角色id的列表
      userRoleIds: [],
      // 是否是不确定的
      isIndeterminate: true,
      // 是否全选
      checkAll: false,
      // 是否正在提交请求中
      loading: false
    }
  },
  mounted() {
    //
    // this.handleQuery()
    this.getUsers()
  },
  methods: {
    // 自定义密码校验
    validatePassword(rule, value, callback) {
      if (!value) {
        callback('密码必须输入')
      } else if (!value || value.length < 6) {
        callback('密码不能小于6位')
      } else {
        callback()
      }
    },
    // 获取分页列表
    async getUsers(pager = 1) {
      //
      this.page = pager
      const { page, limit, searchObj } = this
      this.listLoading = true
      const result = await this.$API.user1.reqPageList(page, limit, searchObj)
      this.listLoading = false
      console.log('分页的列表', result)
      const { items, total } = result.data
      if (result.code === 20000) {
        this.pageList = items.filter(item => {
          console.log('fliter', item)
          return item.username !== 'admin'
        })
        this.total = total - 1
        this.selectedIds = []
        // this.pageList = result.data.items
        // this.total = result.data.total
      }
    },
    // 当PageSize改变时会触发
    handleSizeChange(limit) {
      // console.log('limit', limit)
      this.limit = limit
      this.getUsers()
    },
    // 查询按钮
    async handleQuery() {
      //
      // console.log(123)
      // 浅拷贝
      this.searchObj = { ...this.tempSearchObj }
      this.getUsers()
      // this.queryParams.page = pager
      // const { page, limit, searchObj } = this
      // const result = await this.$API.user1.reqPageList(page, limit, searchObj)
      // console.log('自己封装的分页的列表', result)
      // if (result.code === 20000) {
      //   this.pageList = result.data.items
      //   this.queryParams.total = result.data.total
      // }
    },
    // 清空按钮
    clear() {
      //
      this.tempSearchObj = {
        username: ''
      }
      this.searchObj = {
        username: ''
      }
      this.getUsers()
    },
    // 添加按钮
    handleAdd() {
      // 显示添加用户的界面
      this.user = {}
      this.dialogUserVisible = true
      this.$nextTick(() => {
        this.$refs.userForm.clearValidate()
      })
      // 清楚验证
      // this.$refs['userForm'].resetFields()
    },
    // 表格复选框按钮
    handleSelectionChange(selection) {
      // console.log('selection', selection)
      this.ids = selection.map(item => {
        // console.log(item.id);
        item = item.id
        return item
      })
      // this.ids = selection.map((item) => item.id)
      // console.log('qqqq', this.ids);
      // 非单个禁用
      this.single = selection.length !== 1
      // 非多个禁用
      this.multiple = !selection.length
    },
    // 批量删除
    handleDeletes() {
      // reqBatchRemove
      // console.log(123)
      const ids = this.ids
      // console.log('ids', ids)
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await this.$API.user1.reqBatchRemove(ids)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUsers()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色
    showAssignRole(user) {
      // console.log('分配角色', user)
      this.user = user
      this.dialogRoleVisible = true
      this.getRoles()
    },
    // 异步获取用户的角色列表
    async getRoles() {
      const userId = this.user.id
      // console.log('123', userId)
      const result = await this.$API.user1.reqGetRoles(userId)
      console.log('rrr', result)
      if (result.code === 20000) {
        this.allRoles = result.data.allRolesList
        this.userRoleIds = result.data.assignRoles.map(item => {
          console.log('llll', item)
          item = item.id
          return item
        })
        // console.log('userRoleIds', this.userRoleIds)
        this.checkAll =
          result.data.allRolesList.length === result.data.assignRoles.length
        // console.log('this.checkAll', this.checkAll)
        this.isIndeterminate =
          result.data.assignRoles.length > 0 &&
          result.data.assignRoles.length < result.data.allRolesList.length
        // console.log('this.isIndeterminate', this.isIndeterminate)
      }
    },
    // 修改用户
    showUpdateUser(row) {
      this.dialogUserVisible = true
      this.user = { ...row }
    },
    // 删除用户
    async removeUser(row, id) {
      // console.log('rrr', row)
      await this.$API.user1.reqRemoveById(id)
      this.$message.success('删除成功')
      this.getUsers(this.pageList.length === 1 ? this.page - 1 : this.page)
    },
    // 对话框取消
    cancel() {
      this.dialogUserVisible = false
      // 清空数据
      this.user = {}
    },
    // 添加或者修改的确认
    addOrUpdate() {
      //
      this.$refs['userForm'].validate(async valid => {
        if (valid) {
          const { user } = this
          this.dialogUserVisible = false
          const result = await this.$API.user1.reqAddOrUpdate(user)
          console.log('修改按钮', result)
          if (result.code === 20000) {
            if (this.user.id) {
              this.$message({
                message: '修改成功',
                type: 'warning'
              })
            } else {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            }
            // 添加或者修改成功之后，再次刷新进行显示
            // 如果是添加品牌：停留在第一页，如果是修改品牌，停留在当前页
            this.getUsers(this.user.id ? this.page : 1)
          }
        }
        // if (valid) {
        //   const { user } = this
        //   if (user.id) {
        //     // 修改按钮
        //     const result = await this.$API.user1.reqAddOrUpdate(user)
        //     console.log('修改按钮', result)
        //     if (result.code === 20000) {
        //       this.$message.success('修改成功')
        //       this.dialogUserVisible = false
        //       this.getUsers()
        //     }
        //   } else {
        //     // 添加按钮
        //     const result = await this.$API.user1.reqAddOrUpdate(user)
        //     console.log('添加按钮', result)
        //     if (result.code === 20000) {
        //       this.$message.success('新增成功')
        //       this.dialogUserVisible = false
        //       this.getUsers()
        //     }
        //   }
        // }
      })
    },
    // 全选勾选状态发生改变的监听
    handleCheckAllChange(val) {
      // 是否为全选 true | false
      // console.log('val', val)
      this.userRoleIds = val ? this.allRoles.map(item => item.id) : []
      this.isIndeterminate = false
    },
    // 角色列表选中项发生改变的监听
    handleCheckedChange(val) {
      const { userRoleIds, allRoles } = this
      console.log('handleCheckedChange', val, userRoleIds, allRoles)
      this.checkAll =
        userRoleIds.length === allRoles.length && allRoles.length > 0
      this.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length
      console.log('handleCheckedChange11', this.checkAll, this.isIndeterminate)
    },
    // 请求给用户进行角色授权---保存按钮
    async assignRole() {
      //
      const userId = this.user.id
      // console.log('this.userRoleIds', this.userRoleIds)
      const roleIds = this.userRoleIds.join(',')
      // console.log('roleIds', roleIds)
      this.loading = true
      const result = await this.$API.user1.reqDoAssign(userId, roleIds)
      this.loading = false
      // console.log('保存的result', result)
      if (result.code === 20000) {
        this.$message.success(result.message || '分配角色成功')
        // this.dialogRoleVisible = false
        this.resetRoleData()
      }
      console.log('查看', this.$store.getters.name, this.user)
      if (this.$store.getters.name === this.user.username) {
        window.location.reload()
      }
    },
    // 重置用户角色的数据--取消按钮
    resetRoleData() {
      //
      this.dialogRoleVisible = false
      this.allRoles = []
      this.userRoleIds = []
      this.isIndeterminate = false
      this.checkAll = false
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
